package name.flurl.android.tt_news4android;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JsonNewsParser extends BaseNewsParser {

	public JsonNewsParser(NewsAdapter adapter, URL url) {
		super(adapter);
		mUrl = url;
	}

	@Override
	protected NewsEntry[] doInBackground(Integer... start) {

		NewsEntry[] events = null;
		URL url = getUrl();

		Integer offset = start[0];
		// Log.i("POGA Events offset", offset.toString());
		try {
			url = new URL(url.toString() + "&tx_ttnews[pointer]="
					+ offset.toString());
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		}

		events = fetch(url, offset);
		return events;
	}

	public static NewsEntry[] fetch(URL url, int offset) {
		NewsEntry[] events = null;
		try {
			StringBuilder json = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					getData(url.toString())));
			String line = reader.readLine();
			while (line != null) {
				json.append(line);
				line = reader.readLine();
			}
			events = jsonToEvents(json.toString());
		} catch (Exception e) {
			Log.e("POGA Events", "Exception getting JSON data", e);
			events = null;
		}
		return events;
	}

	public static NewsEntry[] jsonToEvents(String json) throws JSONException {
		NewsEntry[] events;
		JSONObject jsonObj = new JSONObject(json);
		JSONArray eventsArray = jsonObj.getJSONArray("events");
		// Log.i("tt_news4 json", json);

		events = new NewsEntry[eventsArray.length() - 1];

		for (int i = 0; i < eventsArray.length() - 1; i++) {
			JSONObject object = eventsArray.getJSONObject(i);
			// Log.i("POGA Events", object.toString());
			events[i] = new NewsEntry((Long) object.getLong("id"), object
					.getString("title"), (Long) object.getLong("datetime"),
					object.getString("short"), object.getString("bodytext"),
					object.getString("images"), object.getString("categories"),
					object.getString("news_files"), object
							.getString("news_single_link"));
		}
		return events;
	}
}